/*
* @(#)ListUserRecordAction.java
*
* Copyright (c) 2003 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
*/

package com.dcivision.user.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.dao.DmsPersonalStorageSetupDAObject;
import com.dcivision.dms.dao.DmsRootDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractListAction;
import com.dcivision.framework.web.AbstractSearchForm;
import com.dcivision.user.bean.UserGroup;
import com.dcivision.user.bean.UserMember;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.dao.UserGroupDAObject;
import com.dcivision.user.dao.UserRecordDAObject;
import com.dcivision.user.dao.UserRoleDAObject;
import com.dcivision.workflow.dao.MtmWorkflowDynamicUserActorDAObject;
import com.dcivision.workflow.dao.MtmWorkflowStepUserActorDAObject;
/**
 * <p>Class Name:       ListUserRecordAction.java    </p>
 * <p>Description:      The list action class for ListUserRecord.jsp</p>
 * @author           Zoe Shum
 * @company          DCIVision Limited
 * @creation date    08/07/2003
 * @version          $Revision: 1.25.2.1 $
 */
public class ListUserRecordAction extends AbstractListAction {

  public static final String REVISION = "$Revision: 1.25.2.1 $";

  public final static String VAR_USER_GROUP_LIST = "varUserGroupList";
  public final static String VAR_USER_ROLE_LIST = "varUserRoleList";
  /**
   *  Constructor - Creates a new instance of ListUserRecordAction and define the default listName.
   */
  public ListUserRecordAction() {
    super();
    this.setListName("userRecordList");
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.user.dao.UserRecordDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.SETUP_USER_ACCOUNT);
  }

  /**
   * getListData
   *
   * Override the parent's function. Since it required to get the user role
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  public void getListData(ActionMapping mapping, AbstractSearchForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    super.getListData(mapping, form, request, response);

    List listResult = (ArrayList)request.getAttribute(this.getListName());
    /*simon_del_S
    String grantShowAdmin=request.getParameter("grantShowAdmin");
    if(!Utility.isEmpty(grantShowAdmin)){        
    	UserRecord adminUser=this.getAdministrInfo(request);
    	if(!Utility.isEmpty(adminUser) ){
    		listResult.add(adminUser);    	
    	}
    	int startOffset = TextUtility.parseInteger(form.getCurStartRowNo());
    	for(int i=0;i<listResult.size();i++){
    	  UserRecord tmpUserRecord=(UserRecord)listResult.get(i);
    	  tmpUserRecord.setRecordCount(listResult.size());
    	  tmpUserRecord.setRowNum(startOffset++);
    	}
    }*///simon_del_E

    List listRole = new ArrayList();
    List listGroup = new ArrayList();
//    
//    request.setAttribute("myFlag",request.getParameter("pageFlag"));
    
    // Get the user groups and user roles of each user record.
    UserRoleDAObject userRoleDAO = new UserRoleDAObject(this.getSessionContainer(request), this.getConnection(request));
    UserGroupDAObject userGroupDAO = new UserGroupDAObject(this.getSessionContainer(request), this.getConnection(request));
    for (int i=0; i<listResult.size(); i++) {
      UserRecord userRecord = (UserRecord)listResult.get(i);
      listRole.add(userRoleDAO.getListByUserRecordID(userRecord.getID()));
      listGroup.add(userGroupDAO.getListByUserRecordIDGroupType(userRecord.getID(), UserGroup.GROUP_TYPE_PUBLIC));
      
    }
    request.setAttribute(VAR_USER_ROLE_LIST, listRole);
    request.setAttribute(VAR_USER_GROUP_LIST, listGroup);
    
    if(!Utility.isEmpty(request.getParameter("index"))){
      request.setAttribute("index", request.getParameter("index"));
    }
  }
  
  private UserRecord getAdministrInfo(HttpServletRequest request){
	  UserRecord userRecord=null;
	  UserRecordDAObject userRecordDAO = new UserRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
	 
	  try {
		userRecord = (UserRecord)userRecordDAO.getObjectByID(new Integer(0));
		userRecord.getFullName();
		userRecord.getLoginName();
		userRecord.getEmail();
	} catch (Exception e) {
		log.error("Get the Administrator Error! May be the ID isn't 0");
	}
	  return userRecord;
  }
  /**
   *  Method deleteListData() - delete the item(s) from listing page
   *
   *  @param      mapping               ActionMapping from struts
   *  @param      form                  ActionForm from struts
   *  @param      request               HttpServletReuqest
   *  @param      respond               HttpServletRespond
   *  @return     void
   *  @throws     ApplicationException  Throws ApplicationException the deleteion failed
   */
  public void deleteListData(ActionMapping mapping, AbstractSearchForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
  	Connection conn = this.getConnection(request);
  	SessionContainer sessionContainer = this.getSessionContainer(request);
  	String[] basicSelectID = form.getBasicSelectedID();

  	if (!Utility.isEmpty(basicSelectID)){
  		DmsRootDAObject rootDAO = new DmsRootDAObject(sessionContainer,conn);
  		UserRecordDAObject userDAO = new UserRecordDAObject(sessionContainer,conn);
  		MtmWorkflowStepUserActorDAObject mtmWorkflowStepActorDAO=new MtmWorkflowStepUserActorDAObject(sessionContainer,conn);//simon_add
  		MtmWorkflowDynamicUserActorDAObject dynamicUserActorDAO=new MtmWorkflowDynamicUserActorDAObject(sessionContainer,conn);//simon_add
  		String[] tmpBasicSelectID = new String[basicSelectID.length];
  		int tmpBasicSelectIndex = 0;
  		
  		for (int k =0;k < basicSelectID.length; k++){
  			if (Utility.isEmpty(basicSelectID[k])) continue;
  			
  			Integer userRecordID=TextUtility.parseIntegerObj(basicSelectID[k]);
  			UserRecord userRecord = (UserRecord)userDAO.getObjectByID(userRecordID);
  			if(sessionContainer.getUserRecordID().equals(userRecordID)){ 				
  			  this.addError(request, "common.message.cannot_deleted_yourself", userRecord.getLoginName());
  			  continue;
  			}
  			List rootList = rootDAO.getRootByOwnerIDAndType(TextUtility.parseIntegerObj(basicSelectID[k]),DmsRoot.PUBLIC_ROOT,GlobalConstant.RECORD_STATUS_ACTIVE);
  	  		//simon_add_S
  			List userList=mtmWorkflowStepActorDAO.getListWorkflowStepIDByActorIDAndActorType(TextUtility.parseIntegerObj(basicSelectID[k]),UserMember.MEMBER_TYPE_USER);
  			List dynamicUserList=dynamicUserActorDAO.getListWorkflowStepIDByActorIDAndActorType(TextUtility.parseIntegerObj(basicSelectID[k]),UserMember.MEMBER_TYPE_USER);
  			//simon_add_E
  			//if (Utility.isEmpty(rootList)){//simon_del
  			if (Utility.isEmpty(rootList) && Utility.isEmpty(userList) && Utility.isEmpty(dynamicUserList)){//simon_add
  				tmpBasicSelectID[tmpBasicSelectIndex] = basicSelectID[k];
  				++tmpBasicSelectIndex;
  			} else {
  				//Integer userRecordID=TextUtility.parseIntegerObj(basicSelectID[k]);
  				//UserRecord userRecord = (UserRecord)userDAO.getObjectByID(userRecordID);
  				//Bill add for EIP-664 start
  				StringBuffer rootNames=new StringBuffer();
  				if(!Utility.isEmpty(rootList)){
  				  DmsRoot dmsRoot; 
  			      for(int index=0;index<rootList.size();index++){
  			    	dmsRoot=(DmsRoot)rootList.get(index);
  			    	rootNames.append(dmsRoot.getRootName()+" ");
  			      }
  				}
  				this.addError(request, "common.message.records_not_delete", userRecord.getLoginName(),rootNames);
  			   //Bill add for EIP-664 start
  			}
  		}
  		if (tmpBasicSelectIndex > 0){
  			String[] tmp = new String[tmpBasicSelectIndex];
  			for (int m = 0; m < tmpBasicSelectIndex; m++){
    			tmp[m] = tmpBasicSelectID[m]; 
    			form.setBasicSelectedID(tmp);
    		}
  		} else {
  			form.setBasicSelectedID(null);
  		}
  		
  		if (!Utility.isEmpty(form.getBasicSelectedID())) {
  	      super.deleteListData(mapping,form,request,response);
  	      if (((ListUserRecordForm)form).getDeleteStaff().equals("true")) {
  	        UserRecordDAObject  dao = new UserRecordDAObject(sessionContainer,conn);
  	        for (int i=0; i<form.getBasicSelectedID().length; i++) {
  	          dao.deleteRelatedStaffRecord(TextUtility.parseIntegerObj(form.getBasicSelectedID()[i]));
  	        }
  	      }
  	  		DmsPersonalStorageSetupDAObject dmsPersonalStorageSetupDAO=new DmsPersonalStorageSetupDAObject(sessionContainer,conn);
  	      for(int i=0;i<form.getBasicSelectedID().length;i++){
  	        Integer userRecordID=TextUtility.parseIntegerObj(form.getBasicSelectedID()[i]);
  	        dmsPersonalStorageSetupDAO.deleteByMemberIDMemberType(userRecordID,UserMember.MEMBER_TYPE_USER);
  	      }
  	  	}
  	}
  }
}
